/*
 * Author Anju
 */
package com.sdi.columbus;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;





import com.google.android.gms.maps.CameraUpdateFactory;
//import com.example.hellogooglemaps.R;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class GMapActivity extends FragmentActivity  {
    /** Called when the activity is first created. */
	
    private Button btnRefresh;
    private Button btnFocus;
    private Button btnExit;
	private GeoPoint point;
	private MapController mapController;
	private GpsData gpsData;
//	private MapView mapView;
	String result,place;
	private GoogleMap mMap= null;
	
//	int vehicleId;
	String vehicleId;
	GetLatLong get;
	double lat;
	double lng;
	long dates;
	int alt,ang,nos,spd;
	private String dateNTime;
	String response; 
	String date;
	String time,ampm;
//	int custid;
	String accountID;
	String userID;
	String locationmessage,locationdata,pathdate;
	String[] splitData,splitdates;
	String subdate="",dats;
	int regindex;
	String fresult,pathvalues,frmserver;
	String regno;
	Button route;
	Intent path;
	Bundle bpath;
	GpsData gpsa=new GpsData();
	String[] VehicleRegNo=new String[gpsa.getSize()];
//	int [] VehicleIds=new int[gpsa.getSize()];
	String [] VehicleIds=new String[gpsa.getSize()];
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
        setContentView(R.layout.activity_main); 
        VehicleRegNo=gpsa.getVehicleRegNo();
		VehicleIds=gpsa.getVehicleIds();
		accountID = ColombusApp.getSharedApp().accountId;
        Bundle bundle=getIntent().getExtras();
        if(bundle!=null)
        {
//        	vehicleId=bundle.getInt("ID");
        	vehicleId=bundle.getString("ID");
        	
        	for(int q=0;q<gpsa.getSize();q++)
    		{
    			if(VehicleIds[q]==vehicleId)
    			{
    				regindex=q;
    			}
    		}
    		regno=VehicleRegNo[regindex];
        	
    		route=(Button)findViewById(R.id.clickBtn);
        	
        	
//        	System.out.println(" customerid from mapactivity"+custid);
    		System.out.println(" accountid from mapactivity"+accountID);
    		System.out.println(" customerid from mapactivity"+userID);
        	get=new GetLatLong();
        	try
        	{
        	response=get.GetValue(accountID,vehicleId);
        	System.out.println("firstresponds returned");
        	System.out.println("firstresponds"+response);
        	
        	JSONObject json = new JSONObject(response);
			locationmessage = json.getString("GetLatestGPSForVehicleResult");
			
			System.out.println("secondresponds"+locationmessage);
			
			JSONObject jsonl = new JSONObject(locationmessage);
			locationdata=jsonl.getString("LatestGPS");
			
			System.out.println("thirdresponds"+locationdata);
			
			JSONObject jsonloc= new JSONObject(locationdata);
			
			alt=(Integer.parseInt(jsonloc.getString("Altitude")));
		    System.out.println("altitud"+alt);
			
			ang=(Integer.parseInt(jsonloc.getString("Angle")));
			System.out.println("angle"+ang);
			
			lat=Double.parseDouble(jsonloc.getString("Latitude"));
			System.out.println("latitude"+lat);
			
            lng=Double.parseDouble(jsonloc.getString("Longitude"));
            System.out.println("longitude"+lng);
            
			spd=(Integer.parseInt(jsonloc.getString("Speed")));
			System.out.println("speed"+spd);
			
			nos=(Integer.parseInt(jsonloc.getString("NumberOfSatellites")));
			System.out.println("satellite"+nos);
			
        	dateNTime =jsonloc.getString("TimeStamp");
        	System.out.println("stamp"+ dateNTime);
        	
        	int p=dateNTime.indexOf("(");
        	int q=dateNTime.indexOf("+");
        	subdate=dateNTime.substring(p+1, q);
            long dat=Long.parseLong(subdate);
    		SimpleDateFormat formatter = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:ss a");
    		Calendar calendar = Calendar.getInstance();
    	    calendar.setTimeInMillis(dat);
         	dats=formatter.format(calendar.getTime());
    		splitData=dats.split(" ");
            date=splitData[0];
            time=splitData[1];
            ampm=splitData[2];
            
            System.out.println("value from string is"+dats);
            System.out.println("date"+date);
            System.out.println("time"+ time);
        	}
        	catch (Exception e) {
				// TODO: handle exception
			}
        	
        }
        
        this.btnRefresh = (Button)this.findViewById(R.id.btn_refresh);
        this.btnRefresh.setOnClickListener(btnRefresh_onClick);
        this.btnFocus = (Button)this.findViewById(R.id.btn_focus);       
        this.btnFocus.setOnClickListener(btnFocus_onClick);           
        this.btnExit = (Button)this.findViewById(R.id.btn_exit);       
        this.btnExit.setOnClickListener(btnExit_onClick); 
        
//        this.mapView = (MapView) findViewById(R.id.map);
       this.mMap = ((SupportMapFragment)  getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
//        this.mapView.setBuiltInZoomControls(true);
       mMap.animateCamera(CameraUpdateFactory.zoomBy(17.0f));
//        this.mapController = mapView.getController();
//        mapView.setStreetView(true);  
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        Intent intent = getIntent();
        //modified
        this.gpsData = (GpsData)intent.getSerializableExtra("GpsData");
        try {
			ShowPlace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        ShowPoint();
  route.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				showPopUp();
			}
		});
  
             
    } 
    
    private void showPopUp() {

    	 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
    	 helpBuilder.setTitle("Enter Date");
    	 helpBuilder.setMessage("   Format (dd-mm-yyyy) ");
    	 final EditText input = new EditText(this);
    	 input.setSingleLine();
    	 input.setText("");
    	 helpBuilder.setView(input);	 
    	 helpBuilder.setPositiveButton("Done",
    	   new DialogInterface.OnClickListener() {

    	    public void onClick(DialogInterface dialog, int which) {
    	    	
    	    	pathdate=input.getText().toString();
                splitdates=pathdate.split("-");
    	    	FetchPathValues fet=new FetchPathValues(); 
    	        String startt=splitdates[1]+"-"+splitdates[0]+"-"+splitdates[2]+" "+"00:00";
    	        String endt=splitdates[1]+"-"+splitdates[0]+"-"+splitdates[2]+" "+"11:59";
                
    				
					try {
						
						fresult=fet.GetValues(accountID, vehicleId, startt, endt);
	    				JSONObject json = new JSONObject(fresult);
	    			    pathvalues= json.getString("GetGPSForIntervalResult");
	    				JSONObject json1;
						json1 = new JSONObject(pathvalues);
						
	    			    frmserver=json1.getString("StatusMessage");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
    				
    			   
    			    System.out.println("just checking"+fresult);
    				if(!frmserver.equalsIgnoreCase("success"))
    				{	
    					Toast.makeText(GMapActivity.this,frmserver,Toast.LENGTH_LONG).show();
    				}

    				else
    				{
    	    	
    	    	
    	    	      path=new Intent(GMapActivity.this,TraceRoute.class);
    	    	      bpath=new Bundle();
    	    	      bpath.putString("accountID",accountID);
    	    	      bpath.putString("vid",vehicleId);
    	    	      bpath.putString("pdate",pathdate);
    	    	      path.putExtras(bpath);
    	    	      new performBackgroundTask().execute();   
    	            }
    	    	
    	     // Do nothing but close the dialog
    	    }
    	   });

    	 helpBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

    	
    	  public void onClick(DialogInterface dialog, int which) {
    	   // Do nothing
    	  }
    	 });
    	 
    	 
    	 // Remember, create doesn't show the dialog
    	 AlertDialog helpDialog = helpBuilder.create();
    	 helpDialog.show();

    	}
    
    
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
    	MenuInflater inflator=new MenuInflater(GMapActivity.this);
    	inflator.inflate(R.menu.option_menu_main, menu);
		return super.onCreateOptionsMenu(menu);
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		int id=item.getItemId();
		switch(id)
		{
		
		case R.id.refresh:
				new performBackgroundTask().execute();
			return true;
			
		case R.id.focus:
				FocusPoint();
			return true;
			
		case R.id.close:
			    
				Intent intent=new Intent(GMapActivity.this,LoginActivity.class);
				startActivity(intent);
				finish();
			return true;
			
		case R.id.view:
			if(item.getTitle().equals("Satellite View"))
			{
				this.mapController.animateTo(this.point);
			    this.mapController.setZoom(18);
//				mapView.setSatellite(true);
			    mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
//				mapView.setStreetView(false);
			    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//				mapView.invalidate();
				item.setTitle("Street View");
				item.setIcon(R.drawable.mnu_street);
			}
			else if(item.getTitle().equals("Street View"))
			{
				this.mapController.animateTo(this.point);
			    this.mapController.setZoom(18);
//			    mapView.setSatellite(false);
				//mapView.setStreetView(true);
//				mapView.invalidate();
				item.setTitle("Satellite View");
				item.setIcon(R.drawable.mnu_sat);
			}
			return true;
			
		}
		return super.onOptionsItemSelected(item);
	}


	private OnClickListener btnRefresh_onClick = new OnClickListener() {		
		public void onClick(View v) {
			try {
				RefreshPosition();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
	
    private OnClickListener btnFocus_onClick = new OnClickListener() {		
		public void onClick(View v) {
			FocusPoint();
		}
	};
	
    private OnClickListener btnExit_onClick = new OnClickListener() {		
		public void onClick(View v) {
			finish();
		}
	};
	
    private void FocusPoint()
    {
    	this.mapController.animateTo(this.point);
	    this.mapController.setZoom(17);
    }
    
    private void RefreshPosition() throws JSONException, IOException
    {
    	this.gpsData.Login();
    	ShowPlace();
    	ShowPoint();
    }
    public void ShowPlace() throws JSONException, IOException
    
    {
    	
    	JSONObject user =  new JSONObject();
    	user.put("latitude",String.valueOf(lat));
    	user.put("longitude",String.valueOf(lng));
    	
    	// Create a new HttpClient and Post Header
    	
    	HttpClient client = new DefaultHttpClient();
    	URI website;
		try {
			website = new URI("http://deepam.cloudapp.net/ColumbusRESTService/ColumbusREST.svc/json/GetAddressForLatLong");
			HttpPost request = new HttpPost();
	    	request.setEntity(new StringEntity(user.toString()));
	    	request.addHeader("content-type", "application/json");     
	    	request.setURI(website);
	    	
	    	// Execute HTTP Post Request
	    	HttpResponse response = client.execute(request);
	    	HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity);
	    	System.out.println("frm show place"+response);
	    	System.out.println("Response in readable form"+result);
	    	
	    	
	    	JSONObject json = new JSONObject(result);
			String Status = json.getString("GetAddressForLatLongResult");
			
			JSONObject json1 = new JSONObject(Status);
			String Result=json1.getString("PlaceInfo");
			//code=Integer.parseInt(json1.getString("ErrorCode"));
			//UserInfo=json1.getString("UserInfo");
			
			
			
			JSONObject json2 = new JSONObject(Result);
	    	place=json2.getString("FullAddress");
	    	System.out.println("last output"+place);
	    	
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
           
    	
    }
    
    private void ShowPoint()
    {
        int lat =(int)(this.lat * 1E6);
        int lng = (int)(this.lng * 1E6);
        System.out.println("frm mapactivity latitude is"+lat);
        System.out.println("frm map activity longitude is"+lng);
        
        this.point = new GeoPoint(lat,lng);   
    	
//        List<Overlay> mapOverlays = this.mapView.getOverlays();
        List mapOverlays=(List) this.mMap.getMyLocation();
        mapOverlays.clear();
        
        Drawable drawable = this.getResources().getDrawable(R.drawable.imgcaboverlay);        
        GmapItemizedOverlay itemizedoverlay = new GmapItemizedOverlay(drawable,this);        
        
        //String date = this.date.toString().replaceFirst("GMT", "");       

        OverlayItem overlayitem = new OverlayItem(this.point,regno,"Vehicle was last seen here in"+" "+place +" "+ "on"+"                                     "+date+" at " +time+" "+ampm);
        itemizedoverlay.addOverlay(overlayitem);
        mapOverlays.add(itemizedoverlay);

        FocusPoint();
    }
        
    protected boolean isRouteDisplayed() {
        return false;
    }
    
    private class performBackgroundTask extends AsyncTask < Void, Void, Void > 
    {
		
       private ProgressDialog pdia;

       @Override
       protected void onPreExecute(){
          super.onPreExecute();
               pdia = new ProgressDialog(GMapActivity.this);
               pdia.setMessage("Please Wait....");
               pdia.show();
               System.out.println("In onPreExecute");       
       }
 
       @Override
       protected Void doInBackground(Void... params) {
    	   System.out.println("In doInBackground");
    	   startActivity(path);
    	   return null;
       }

       @Override
       protected void onPostExecute(Void result) {
    	   super.onPostExecute(result);
    	   System.out.println("In onPostExecute");
    	   pdia.dismiss();
       }

       @Override
       protected void onProgressUpdate(Void... values) {
    	   super.onProgressUpdate(values);
    	   System.out.println("In onProgressUpdate");
       }

    }
}
